package org.deyang.tools.amazon.services;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.deyang.tools.amazon.pojos.AmazonResultEntry;
import org.deyang.tools.amazon.pojos.DealDetail;
import org.deyang.tools.amazon.pojos.PriceInformation;
import org.deyang.tools.amazon.pricetracker.KeepaPriceTracker;
import org.deyang.tools.amazon.utils.AmazonXMLProcessor;
import org.deyang.tools.amazon.utils.PriceUtils;
import org.deyang.tools.amazon.utils.SignedRequestsHelper;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ItemSearchService {
	
	private List<AmazonResultEntry> searchResultList = new ArrayList<AmazonResultEntry>();
	private static final Logger log = Logger.getLogger(ItemSearchService.class.getName());
	

    /*
     * Your AWS Access Key ID, as taken from the AWS Your Account page.
     */
    private static final String AWS_ACCESS_KEY_ID = "AKIAIAHIG7YUEG5T3SJQ";

    /*
     * Your AWS Secret Key corresponding to the above ID, as taken from the AWS
     * Your Account page.
     */
    private static final String AWS_SECRET_KEY = "t/wfJkvXEzfaDDYJ6aEvE64CwyplG/VYxuv61QBf";

    /*
     * Use one of the following end-points, according to the region you are
     * interested in:
     * 
     *      US: ecs.amazonaws.com 
     *      CA: ecs.amazonaws.ca 
     *      UK: ecs.amazonaws.co.uk 
     *      DE: ecs.amazonaws.de 
     *      FR: ecs.amazonaws.fr 
     *      JP: ecs.amazonaws.jp
     * 
     */
    private static final String ENDPOINT = "webservices.amazon.com";

    /*
     * The Item ID to lookup. The value below was selected for the US locale.
     * You can choose a different value if this value does not work in the
     * locale of your choice.
     */
    
    public List<AmazonResultEntry> doItemSearch(String keyword,String searchindex, String pageIndex){
        /*
         * Set up the signed requests helper 
         */
        SignedRequestsHelper helper = null;
        try {
            helper = SignedRequestsHelper.getInstance(ItemSearchService.ENDPOINT, ItemSearchService.AWS_ACCESS_KEY_ID, ItemSearchService.AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return searchResultList;
        }
        
        Properties prop = System.getProperties(); 
		prop.put("http.proxyHost","202.3.9.229"); 
		prop.put("http.proxyPort","3128"); 

        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("AssociateTag", "doherty-20");
        params.put("Operation", "ItemSearch");
        params.put("Keywords", keyword);
        params.put("ItemPage", pageIndex);
        params.put("MinPercentageOff", "20");
        params.put("Condition", "New");
        //params.put("Availability", "Available");
        params.put("SearchIndex", searchindex);
        params.put("ResponseGroup", "Medium,Offers,OfferFull");
        
        String requestUrl = helper.sign(params);
        
        try {
			URL url = new URL(requestUrl);
			log.info(requestUrl);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        	DocumentBuilder db = dbf.newDocumentBuilder();
        	org.w3c.dom.Document domDoc = db.parse(url.openStream());
        	NodeList itemList = domDoc.getElementsByTagName("Item");
        	
        	for (int i = 0; i < itemList.getLength(); i++){
        		Element itemElement = (Element) itemList.item(i);
        		AmazonResultEntry resultEntry = new AmazonResultEntry();
        		String asin = AmazonXMLProcessor.getDefaultChildNodeValue((Element) itemElement, "ASIN");
        		resultEntry.setAsinValue(asin);
        		if (!asin.equals("")){
        			//Add to price track list
        			resultEntry.setAvailableForPriceTracking(true);
        		}
        		resultEntry.setLinkURL(AmazonXMLProcessor.getDefaultChildNodeValue(itemElement, "DetailPageURL"));
        		
        		Element mediumImageElement = AmazonXMLProcessor.getDefaultChildNode(itemElement, "MediumImage");
        		resultEntry.setMediumImageURL(AmazonXMLProcessor.getDefaultChildNodeValue(mediumImageElement, "URL"));
        		
        		Element arrtElement = AmazonXMLProcessor.getDefaultChildNode(itemElement, "ItemAttributes");
        		resultEntry.setOrignialProductTitle(AmazonXMLProcessor.getDefaultChildNodeValue(arrtElement, "Title"));
        		
        		//Check whether it is a deal
        		PriceInformation pi = PriceUtils.getCurrentLowPrice(itemElement, true);
        		KeepaPriceTracker kpt = new KeepaPriceTracker(resultEntry.getAsinValue(),pi);
        		if (kpt.isDeal(30)){
        			DealDetail dd = kpt.getDealDetail();
        			if (dd.isAmazonDeal()){
        				resultEntry.setDealDetail(dd);
        				resultEntry.setFormattedPrice(pi.getAmazonPrice());
        			}else if (dd.isMarketDeal()){
        				resultEntry.setDealDetail(dd);
        				resultEntry.setFormattedPrice(pi.getThirdPartyPrice());
        			}
        		}else{
        				if (pi.isAmazonPriceAvailable()){
        					resultEntry.setFormattedPrice(pi.getAmazonPrice());
        				}else if(pi.isThirdPartyPriceAvailable()){
        					resultEntry.setFormattedPrice(pi.getThirdPartyPrice());
        				}else{
        					resultEntry.setFormattedPrice("No available price");
        				}
        				
        		}
        		searchResultList.add(resultEntry);
        	}			
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
        return searchResultList;
    }



    
}
